//
//  NETWorkTool.swift
//  AFTest
//
//  Created by adel on 2017/8/21.
//  Copyright © 2017年 adel. All rights reserved.
//

import UIKit
import AFNetworking

enum requestType:String {
    case GET = "GET"
    case POST = "POST"
}

class NETWorkTool: AFHTTPSessionManager {
    //单例对象
    static let sharedNETWorkTool:NETWorkTool = {
        let tools = NETWorkTool()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        tools.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
        return tools
    }()
    
}


// MARK:封装网络请求
extension NETWorkTool{
    
    
    func request(requesType:requestType, urlString:String,parameters:[String:Any],finished: @escaping ( _ result : Any?, _ error:Error?) -> ()) {
        
        
        let successCallBack = { (task:URLSessionDataTask, result:Any?) in
            finished(result, nil)
        };
        
        
        let failureCallBack = { (task:URLSessionDataTask?,error:Error) in
            finished(nil, error)
        };
        
        
        
        if requesType == .GET {
            
            get(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
            
            
        }else{
        
            post(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }
    }
}

// MARK:- 请求AccessToken
extension NETWorkTool{

     func loadAccessToken(code : String, finished : @escaping (_ result : [String : AnyObject]?, _ error : NSError?) -> ()) {
    
        // 1.获取请求的URLString
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // 2.获取请求的参数
        let parameters = ["client_id" : app_key, "client_secret" : app_secret, "grant_type" : "authorization_code", "redirect_uri" : redirect_uri, "code" : code]
        
        // 3.发送网络请求
        
        request(requesType: .POST, urlString: urlString, parameters: parameters) { (result, error) -> ()  in
            
            if error != nil {
                
                finished(nil, error! as NSError)
                
            }else{
                
                finished(result as? [String : AnyObject], nil)
            }

        }
        
    }
}

// MARK:- 请求用户信息
extension NETWorkTool{
    
    func loadUserInfo(access_token : String, uid : String, finished :@escaping (_ result : [String : AnyObject]?, _ error : NSError?) ->()) {
        
        // 1.获取请求的URLString
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        // 2.获取请求的参数
        let parameters = ["access_token" : access_token, "uid" : uid]
        
        // 3.发送网络请求
        request(requesType: .GET, urlString: urlString, parameters: parameters) { (result, error) -> () in
            
            if error != nil {
                
                finished(nil, error! as NSError)
                
            }else{
                
                finished(result as? [String : AnyObject], nil)
            }
            
        }
    }

}

// MARK:- 请求首页微博数据
extension NETWorkTool{
    
    func loadStatuses(since_id : Int, max_id : Int, finished : @escaping (_ result : [[String : AnyObject]]?, _ error : NSError?) -> ()) {
        
        // 1.获取请求的URLString
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        // 2.获取请求的参数
        
        let accessToken = (UserAccountViewModel.sharedUserAccountViewModel.account?.access_token)!
        let parameters = ["access_token" : accessToken, "since_id" : "\(since_id)", "max_id" : "\(max_id)"]
        
        request(requesType: .GET, urlString: urlString, parameters: parameters as Any as! [String : Any]) {(result, error) in
            
            // 1.获取字典的数据
            guard let resultDict = result as? [String : AnyObject] else {
                finished(nil, error! as NSError)
                return
            }
            
            finished(resultDict["statuses"] as? [[String : AnyObject]], nil)
        
        }
    }
    
}

// MARK:- 发送微博
extension NETWorkTool{
    
    
    func sendStatus(_ statusText : String, isSuccess : @escaping (_ isSuccess : Bool) -> ()) {
        // 1.获取请求的URLString
        print(statusText)
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        // 2.获取请求的参数
        let parameters = ["access_token" : (UserAccountViewModel.sharedUserAccountViewModel.account?.access_token)!,"status": statusText]
        
        request(requesType: .POST, urlString: urlString, parameters: parameters) { (result, error) in
            if (error != nil) {
                print(error!)
            }
            if result != nil {
                
                isSuccess(true)
            } else {
                isSuccess(false)
            }
        }
    }
    
}
